﻿var Movie = require('../models/movie')
var Catetory = require('../models/catetory')
//首页
exports.index = function(req,res){
	console.log('session users:')
	console.log(req.session.user)

	Catetory.find({})
	.populate({path:'movies',options:{limit:5}})
	.exec(function(err,catetoryies){
		if(err){
			console.log(err);
		}
		res.render('index',{
			title:'imooc 首页',
			catetory:catetoryies
		})

	})
}

//首页
exports.search = function(req,res){
	var catId = req.query.cat
	var page = parseInt(req.query.p,10) || 0;
	var count = 2;
	var index = page*count;
	var q = req.query.q;

	if(catId){
		Catetory.find({_id:catId})
		.populate({
			path:'movies',
			select:'title poster'
		})
		.exec(function(err,catetoryies){
			if(err){
				console.log(err);
			}

			var catetory = catetoryies[0] || {};
			var movies = catetory.movies || [];
			var result = movies.slice(index, index+count);

			res.render('results',{
				title:'imooc 结果列表',
				keyword:catetory.name,
				currentpage:(page+1),
				query:'cat='+catId,
				totlepage:Math.ceil(movies.length/2),
				movies:result
			})

		})
	}else{
		Movie.find({title:new RegExp(q+'.*','i')})
		.exec(function(err,movies){
			if(err){
				console.log(err);
			}

			var result = movies.slice(index, index+count);

			res.render('results',{
				title:'imooc 结果列表',
				keyword:q,
				currentpage:(page+1),
				query:'cat='+catId,
				totlepage:Math.ceil(movies.length/2),
				movies:result
			})

		})
	}

}